package com.rzjm.api.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.dao.PickUpPlanDao;
import com.rzjm.api.dao.PickUpPlanInfoDao;
import com.rzjm.api.dao.PickUpRecordDao;
import com.rzjm.api.dao.PickUpRecordMatterDao;
import com.rzjm.api.entity.*;
import com.rzjm.api.exception.TransactionalException;
import com.rzjm.api.service.PickUpRecordService;
import com.rzjm.api.service.WxTemplateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;

@Service
public class PickUpRecordServiceImpl extends BaseServiceImpl<PickUpRecordDao, PickUpRecord> implements PickUpRecordService {

    @Resource
    private PickUpRecordDao recordDao;
    @Resource
    private PickUpPlanDao planDao;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private PickUpPlanInfoDao planInfoDao;
    @Resource
    private PickUpRecordMatterDao pickUpRecordMatterDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addRecord(User user, PickUpPlanInfo planInfo, PickUpRecord record) {
        int ret = 0;
        try{
//            PickUpPlan plan = planDao.selectById(planInfo.getPlanId());
//            if(plan!=null){

                ret = recordDao.insert(record);
                if(ret <= 0){
                    throw new TransactionalException("recordDao insert error");
                }
                if (record.getMattersArray() != null && record.getMattersArray().size() > 0){
                    for (int i = 0; i < record.getMattersArray().size(); i++) {
                        JSONObject jsonObject = record.getMattersArray().getJSONObject(i);
                        PickUpRecordMatter pickUpRecordMatter = new PickUpRecordMatter();
                        pickUpRecordMatter.setPickUpRecordId(record.getId());
                        pickUpRecordMatter.setWuLiaoName((String) jsonObject.get("wuliao_name"));
                        pickUpRecordMatter.setWuLiaoWeight( Double.parseDouble((String) jsonObject.get("wuliao_weight")));
                        pickUpRecordMatterDao.insert(pickUpRecordMatter);
                    }
                }

//                planInfo.setState(1);
//                ret = planInfoDao.updateById(planInfo);
//                if(ret <= 0){
//                    throw new TransactionalException("planInfoDao updateById error");
//                }

                //发送推送消息
                wxTemplateService.sendWxMsgCarYuyue(record);
//            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }
        return ret;
    }

    @Override
    @Transactional
    public int sign(User user, PickUpRecord record) {
        int ret = 0;
        try{
            PickUpPlan plan = planDao.selectById(record.getPlanId());
            if(plan !=null){
                int regCount = plan.getRegCount();
                record.setRecordNo("A" + String.format("%04d",(regCount + 1)));

                plan.setRegCount(regCount + 1);
                ret = planDao.updateById(plan);
                if(ret <= 0){
                    throw new TransactionalException("planDao insert error");
                }
            }

            //状态 0 - 预约成功   1 - 签到成功（叫号成功）  2 - 过号排队中  3 - 取货完成
            record.setState(1);
            record.setAppointmentTime(new Date());
            ret = recordDao.updateById(record);
            if(ret <= 0){
                throw new TransactionalException("recordDao insert error");
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }


    @Override
    @Transactional
    public int call(User user, PickUpPlan plan,int isStride) {
        int ret = 0;
        try{
            //在叫号之前 先将 已经在叫号中的 修改成 已取货完成
//            状态 0 - 预约成功   1 - 签到成功（叫号成功）  2 - 过号排队中  3 - 取货完成
            // 过号

            //找出 第一个 签到叫号的记录
            QueryWrapper<PickUpRecord> qw = new QueryWrapper<>();
            qw.eq("plan_id", plan.getId());
            qw.eq("state", 1);
            qw.eq("call_state", 0);
            qw.orderByAsc("appointment_time");
            qw.last("limit 1");
            PickUpRecord newRecord = recordDao.selectOne(qw);
            if(newRecord == null){
                return -1;
            }

            //isStride  0 - 正常叫号  1 - 过号
            Date nowAppointmentTime = null;
            if(isStride == 1){
                QueryWrapper<PickUpRecord> qwNow = new QueryWrapper<>();
                qwNow.eq("plan_id", plan.getId());
                qwNow.eq("state", 1);
                qwNow.eq("call_state", 1);
                qwNow.last("limit 1");
                PickUpRecord nowRecord = recordDao.selectOne(qwNow);
                if(nowRecord != null){
                    nowAppointmentTime = nowRecord.getAppointmentTime();
                    nowRecord.setCallState(0);
                    nowRecord.setAppointmentTime(newRecord.getAppointmentTime());

                    ret = recordDao.updateById(nowRecord);
                    if(ret <= 0){
                        throw new TransactionalException("recordDao updateById error");
                    }
                }
            } else {
                //修改 之前 已经叫号过的 设置成 结束状态
                lambdaUpdate().set(PickUpRecord::getState, 3)
                        .set(PickUpRecord::getCallState, 0)
                        .eq(PickUpRecord::getPlanId, plan.getId())
                        .eq(PickUpRecord::getState, 1)
                        .eq(PickUpRecord::getCallState, 1).update();
            }

            if(newRecord != null){
                newRecord.setCallState(1);
                if(nowAppointmentTime!=null){
                    newRecord.setAppointmentTime(nowAppointmentTime);
                }
                ret = recordDao.updateById(newRecord);
                if(ret <= 0){
                    throw new TransactionalException("recordDao updateById error");
                }
            }
            //发送推送消息
            if(isStride == 0){
//                wxTemplateService.sendWxMsgPickUpCall(user,newRecord);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    @Override
    @Transactional
    public int jump(User user, PickUpRecord record) {
        int ret = 0;
        try{
            //找出 下一个 签到叫号的记录
            QueryWrapper<PickUpRecord> qw = new QueryWrapper<>();
            qw.eq("plan_id", record.getPlanId());
            qw.eq("state", 1);
            qw.eq("call_state", 0);
            qw.orderByAsc("appointment_time");
            qw.last("limit 1");
            PickUpRecord nextRecord = recordDao.selectOne(qw);

            QueryWrapper<PickUpRecord> qwNow = new QueryWrapper<>();
            qwNow.eq("plan_id", record.getPlanId());
            qwNow.eq("state", 1);
            qwNow.eq("call_state", 1);
            qwNow.last("limit 1");
            PickUpRecord nowRecord = recordDao.selectOne(qwNow);
            if(nowRecord != null){
                nowRecord.setCallState(0);
                nowRecord.setState(3);
                ret = recordDao.updateById(nowRecord);
                if(ret <= 0){
                    throw new TransactionalException("recordDao updateById error");
                }
            }

            Date jumpTime = nextRecord.getAppointmentTime();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(jumpTime);
            calendar.add(Calendar.SECOND,-1);
            jumpTime = calendar.getTime();

            record.setCallState(1);
            record.setAppointmentTime(jumpTime);
            ret = recordDao.updateById(record);
            if(ret <= 0){
                throw new TransactionalException("recordDao updateById error");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }


    @Override
    public PickUpRecord getMyLastRecord(User user, PickUpPlanInfo planInfo, int state) {
        QueryWrapper<PickUpRecord> qw = new QueryWrapper<>();
        qw.eq("user_id",user.getId());
        qw.eq("plan_id",planInfo.getPlanId());
        qw.eq("state",state);
        qw.orderByDesc("appointment_time");
        qw.last("limit 1");
        return recordDao.selectOne(qw);
    }
}
